package com.zkc.bootnew.controller;

import com.zkc.springbootnew.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * 文件上传
 */
@Controller
public class FileController {
    @ResponseBody
    @RequestMapping(value = "/uploads",method = RequestMethod.POST)
    public Dto upload(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest request, HttpSession session){
        Dto msg = new Dto();
        if (imgFile.isEmpty()) {
            return DtoUtil.returnDataSuccess("上传失败，请选择文件");
        }
        // 拿到文件名
        String filename = imgFile.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf("."));//后缀名
        filename= UUID.randomUUID()+suffixName;//图片名
        // 存放上传图片的文件夹
        File fileDir = UploadUtils.getImgDirFile();
        // 输出文件夹绝对路径  -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
        // System.out.println(fileDir.getAbsolutePath());
        try {
            // 构建真实的文件路径
            File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
            //System.out.println(newFile.getAbsolutePath());
            // 上传图片到 -》 “绝对路径”
            imgFile.transferTo(newFile);
            msg.setMsg("上传成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DtoUtil.returnDataSuccess(filename);
    }


    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @PostMapping("/upload")
    @ResponseBody
    public Dto updateAvatar(@RequestParam("imgFile") MultipartFile imgFile) throws IOException {

        if (!imgFile.isEmpty()) {
            File fileDir =Global.getImgDirFile();
            String avatar = FileUploadUtils.upload(fileDir, imgFile);
            System.out.println("------------------------"+avatar);
            return DtoUtil.returnDataSuccess(avatar);
        }
        return DtoUtil.returnDataSuccess("修改头像失败！");
    }


    //将磁盘文件路径映射为项目访问路径
    @Configuration
    public class WebMvcConfiguration implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/img/**").addResourceLocations("file:/img/");
        }
    }

}

